import {
    loginByUsername,
    logout
} from '@/api/login'
import {
    getToken,
    setToken,
    removeToken,
    setLocalStorage,
    getLocalStorage,
    removeLocalStorage,
    setKey,
    removeKey
} from '@/utils/auth'

const user = {
    state: {
        userInfo: {},
        token: getToken(),
        a:1,
        selectedIndex:'0-0'
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo
        }
    },

    actions: {
        LoginByUsername({
            commit
        }, userInfo) {
            const username = userInfo.usrLogin.trim()
            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.usrPwd).then(response => {
                    const data = response
                    commit('SET_TOKEN', data.result.token)
                    commit('SET_USERINFO', data.result)
                    setToken(response.result.shiroToken) //需要权限 传的的token
                    setKey(response.result.key) 
                    // setToken('SFKN9nZVy0vOod95aEGe2HKRlIPZt91ykkipolBe')
                    setLocalStorage('USERINFO', data);
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })

        },
         // 登出
    LogOut({
        commit
      }) {
        return new Promise((resolve, reject) => {
            debugger;
          logout({
            usrId:getLocalStorage('USERINFO').result.user.usrId,
            token: getLocalStorage("USERINFO").result.token,
          }).then(() => {
            commit('SET_TOKEN', '')
            removeLocalStorage('USERINFO');
            removeToken()
            removeKey()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
    }
}

export default user